package com.xiangwei.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;






import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiangwei.entity.Image;
import com.xiangwei.entity.Product;
import com.xiangwei.entity.Template;
import com.xiangwei.entity.Vendor;
import com.xiangwei.service.IImageService;
import com.xiangwei.service.IProductService;
import com.xiangwei.service.IQrcodeService;
import com.xiangwei.service.ITemplateService;
import com.xiangwei.service.IVendorService;
import com.xiangwei.util.Common;
import com.xiangwei.util.DateUtils;
import com.xiangwei.util.FileOperation;
import com.xiangwei.util.FileToZip;
import com.xiangwei.util.PageUtil;
import com.xiangwei.util.QiniuUtil;
import com.xiangwei.util.ReadPropertiesUtil;
import com.xiangwei.util.StringUtils;
import com.xiangwei.util.getDate;
import com.xiangwei.util.zxing.QrcodeConfig;
import com.xiangwei.util.zxing.QrcodeFactory;
import com.xiangwei.view.ProductView;
import com.xiangwei.view.VendorView;

@Controller
@RequestMapping(value = "admin")
public class ProductController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

	private IProductService iproductService;
	private IQrcodeService iqrcodeService;
	private IVendorService ivendorService;
	@Resource
	private IImageService imageService;
	@Resource
	private ITemplateService templateService;
	
	public IProductService getIproductService() {
		return iproductService;
	}

	@Resource
	public void setIproductService(IProductService iproductService) {
		this.iproductService = iproductService;
	}

	public IQrcodeService getIqrcodeService() {
		return iqrcodeService;
	}
	
	@Resource
	public void setIqrcodeService(IQrcodeService iqrcodeService) {
		this.iqrcodeService = iqrcodeService;
	}

	public IVendorService getIvendorService() {
		return ivendorService;
	}
	
	@Resource
	public void setIvendorService(IVendorService ivendorService) {
		this.ivendorService = ivendorService;
	}

	/**
	 * 显示该公司下的所有产品信息
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getAll", method = RequestMethod.GET)
	public String getAll(Model model, HttpServletRequest request, String page) {
		Integer start = 0;     //分页查询的开始行
		Integer pageSize = 5;       //分页查询的每页页数
		HttpSession session = request.getSession();
	     session.setAttribute("vendorId",1L);     //工厂的数据库id，测试数据
	     Integer allCount = iproductService.getCount();       //获取总数
	     Integer currentPage = 1;
	     if(page!=null){            //如果目前所在页码不为null，就作为当前页码
	    	 currentPage = Integer.valueOf(page);
	    	 start = start + pageSize * (currentPage-1);
	     }
	     Map<String,Object> listPage = PageUtil.getPage(pageSize, allCount, currentPage);   //存放分页信息
		 model.addAttribute("productList",iproductService.getAll(start,pageSize));
		 model.addAttribute("listPage",listPage);
		return "admin/product";
	}
	
	/**
	 * 获取所有产品信息
	 * @param model
	 * @param request
	 * @param vendorId
	 * @return
	 */
	@RequestMapping(value = "productList", method = RequestMethod.GET)
	public String getProductList(Model model, HttpServletRequest request, String vId) {
		HttpSession session = request.getSession();
		if(!Common.isEmptyString(vId)){
			vId = (String) session.getAttribute("vId");
		}
		session.removeAttribute("vId");
		session.setAttribute("vId", vId);
		
		Integer id = Integer.parseInt(vId);
	    VendorView vv = ivendorService.selectVendorViewById(id);
	    String vendorInfo = vv.getVendor().getInfo();
	    vendorInfo = vendorInfo.replaceAll(" ","&nbsp;").replaceAll("\r","<br/>");
	    vv.getVendor().setInfo(vendorInfo);
		model.addAttribute("productList",iproductService.getProductList(id));
		
		Image img= new Image();//多图
		img.setPid(id);
		img.setType(Short.parseShort("0"));//厂商多图关联类型为0
		List<Image> imgList = imageService.getImagesByPidAndType(img);
		model.addAttribute("imgList", imgList);
		//查询产品列表
		model.addAttribute("vendorView",vv);
		model.addAttribute("imageUrl",QiniuUtil.IMAGEURL);
		return "admin/productList";
	}
	
	/**
	 * 跳转至新增页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addProduct", method = RequestMethod.GET)
	public String add(Model model) {
		model.addAttribute("sign", "add");
		List<Template> t = templateService.selectTemplateList();
		if(!Common.isNullOrEmpty(t) && t.size() > 0){
			model.addAttribute("template", t.get(0));			
		}
		return "admin/addProduct";
	}
	
	/**
	 * 检查产品名称是否已经重复了
	 * @param productName
	 * @return
	 */
	@RequestMapping(value = "checkName", method = RequestMethod.POST)
	public void checkName(String pName, String vId,String id,HttpServletRequest request, HttpServletResponse response) {
		HttpSession  session = request.getSession();
		if(!Common.isEmptyString(vId)){
			vId = (String) session.getAttribute("vId");
		}
		String msg = "fail";
		int count = iproductService.checkProductName(pName,vId,id);
		if(count == 0){
			msg = "success";
		}
		try {
			response.getWriter().print(msg);//fail表示已经重复
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}    
		
	}
	
	/**
	 * 在数据库新增产品数据
	 * @param product
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "addProducting", method = RequestMethod.POST)
	@Transactional
	public void addProduct(@ModelAttribute Product product,String[] cName,String[] cValue,String date,
			String[] eId, HttpServletRequest request,HttpServletResponse response,
			@RequestParam("fileLogo")MultipartFile fileLogo,@RequestParam("fileVideo")MultipartFile fileVideo, 
			@RequestParam("fileVideoImg")MultipartFile fileVideoImg,String fileVideoAdd,String sign,HttpSession session) throws IOException {

		
		
		
		if(fileLogo!=null&&!fileLogo.isEmpty()){
    		// 文件保存路径  
			String fileName = getDate.getStringFullDate()+fileLogo.getOriginalFilename();      //文件名称
            String filePath = request.getSession().getServletContext().getRealPath("/") + "uploadImage/"  
                    + fileName;  
            // 如果不存在，则创建目录
            if (!new File(filePath).isDirectory()){
            	new File(filePath).mkdirs();
            }
            try {
            	// 转存文件
            	File files = new File(filePath);
            	fileLogo.transferTo(files);
            	product.setLogo(fileName);
            	String success = QiniuUtil.upload(filePath, fileName);         //上传到七牛云服务
            	if(success!=null){
            		files.delete();          //如果上传成功，就删除本地服务的图片
            	}
			} catch (IllegalStateException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalStateException("文件上传失败");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IOException("文件上传失败");
			} 
    	}
		
		if(fileVideo != null && !fileVideo.isEmpty() && product.getVideoType() == 0 ){
    		// 文件保存路径  
			String fileName = getDate.getStringFullDate()+fileVideo.getOriginalFilename();      //文件名称
            String filePath = request.getSession().getServletContext().getRealPath("/") + "uploadVideo/"  
                    + fileName;  
            // 如果不存在，则创建目录
            if (!new File(filePath).isDirectory()){
            	new File(filePath).mkdirs();
            }
            try {
            	// 转存文件
            	File files = new File(filePath);
            	System.out.println("filePath="+filePath);
            	fileVideo.transferTo(files);
            	product.setVideo(fileName);

			} catch (IllegalStateException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalStateException("文件上传失败");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IOException("文件上传失败");
			}             
    	}else if(Common.isEmptyString(fileVideoAdd) && product.getVideoType() == 1){
    		fileVideoAdd = fileVideoAdd.replace("http://", "").replace("https://", "");
    		product.setVideo(fileVideoAdd);
    	}
		
		if(fileVideoImg!=null&&!fileVideoImg.isEmpty()){
    		// 文件保存路径  
			String fileName = getDate.getStringFullDate()+fileVideoImg.getOriginalFilename();      //文件名称
            String filePath = request.getSession().getServletContext().getRealPath("/") + "uploadImage/"  
                    + fileName;  
            // 如果不存在，则创建目录
            if (!new File(filePath).isDirectory()){
            	new File(filePath).mkdirs();
            }
            try {
            	// 转存文件
            	File files = new File(filePath);
            	fileVideoImg.transferTo(files);
            	product.setVideoImg(fileName);
            	String success = QiniuUtil.upload(filePath, fileName);         //上传到七牛云服务
            	if(success!=null){
            		logger.info("上传成功");
            		files.delete();          //如果上传成功，就删除本地服务的图片
            	}
			} catch (IllegalStateException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalStateException("文件上传失败");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IOException("文件上传失败");
			} 
    	}	

		if(Common.isEmptyString(date)){
			SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.PATTEN_YMD);
			try {
				Date d = sdf.parse(date);
				product.setProduceDate(d);
			} catch (ParseException e) {
				logger.error(e.getMessage());
			}
		}
		Integer id = product.getId();
		if(id != null){    //表示编辑
			iproductService.updateByPrimaryKey(product,cName,cValue,eId);
			session.setAttribute("productId", product.getId()+"");

		}else{               //否则就新增
			iproductService.insert(product,cName,cValue);
			Product p = iproductService.getMaxIdProduct();
			session.setAttribute("productId", p.getId()+"");
		}
		try {
			response.getWriter().print("success");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
		}
		
	}
	
	
	@RequestMapping(value = "saveProducting", method = RequestMethod.POST)
	@Transactional
	public String saveProduct(@ModelAttribute Product product,String[] cName,String[] cValue,String date,
			String[] eId, HttpServletRequest request,HttpServletResponse response, 
			@RequestParam("fileLogo")MultipartFile fileLogo,@RequestParam("fileVideo")MultipartFile fileVideo, 
			@RequestParam("fileVideoImg")MultipartFile fileVideoImg,String fileVideoAdd,String sign,HttpSession session) throws IOException {
		
		
		
		if(fileLogo!=null&&!fileLogo.isEmpty()){
    		// 文件保存路径  
			String fileName = getDate.getStringFullDate()+fileLogo.getOriginalFilename();      //文件名称
            String filePath = request.getSession().getServletContext().getRealPath("/") + "uploadImage/"  
                    + fileName;  
            // 如果不存在，则创建目录
            if (!new File(filePath).isDirectory()){
            	new File(filePath).mkdirs();
            }
            try {
            	// 转存文件
            	File files = new File(filePath);
            	fileLogo.transferTo(files);
            	product.setLogo(fileName);
            	String success = QiniuUtil.upload(filePath, fileName);         //上传到七牛云服务
            	if(success!=null){
            		files.delete();          //如果上传成功，就删除本地服务的图片
            	}
			} catch (IllegalStateException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalStateException("文件上传失败");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IOException("文件上传失败");
			} 
    	}
		
		if(fileVideo != null && !fileVideo.isEmpty() && !Common.isEmptyString(fileVideoAdd) ){
    		// 文件保存路径  
			String fileName = getDate.getStringFullDate()+fileVideo.getOriginalFilename();      //文件名称
            String filePath = request.getSession().getServletContext().getRealPath("/") + "uploadVideo/"  
                    + fileName;  
            // 如果不存在，则创建目录
            if (!new File(filePath).isDirectory()){
            	new File(filePath).mkdirs();
            }
            try {
            	// 转存文件
            	File files = new File(filePath);
            	System.out.println("filePath="+filePath);
            	fileVideo.transferTo(files);
            	product.setVideo(fileName);

			} catch (IllegalStateException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalStateException("文件上传失败");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IOException("文件上传失败");
			}             
    	}else if(Common.isEmptyString(fileVideoAdd)){
    		fileVideoAdd = fileVideoAdd.replace("http://", "").replace("https://", "");
    		product.setVideo(fileVideoAdd);
    	}
		
		if(fileVideoImg!=null&&!fileVideoImg.isEmpty()){
    		// 文件保存路径  
			String fileName = getDate.getStringFullDate()+fileVideoImg.getOriginalFilename();      //文件名称
            String filePath = request.getSession().getServletContext().getRealPath("/") + "uploadImage/"  
                    + fileName;  
            // 如果不存在，则创建目录
            if (!new File(filePath).isDirectory()){
            	new File(filePath).mkdirs();
            }
            try {
            	// 转存文件
            	File files = new File(filePath);
            	fileVideoImg.transferTo(files);
            	product.setVideoImg(fileName);
            	String success = QiniuUtil.upload(filePath, fileName);         //上传到七牛云服务
            	if(success!=null){
            		logger.info("上传成功");
            		files.delete();          //如果上传成功，就删除本地服务的图片
            	}
			} catch (IllegalStateException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalStateException("文件上传失败");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IOException("文件上传失败");
			} 
    	}	

		if(Common.isEmptyString(date)){
			SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.PATTEN_YMD);
			try {
				Date d = sdf.parse(date);
				product.setProduceDate(d);
			} catch (ParseException e) {
				logger.error(e.getMessage());
			}
		}
		Integer id = product.getId();
		if(id != null){    //表示编辑
			iproductService.updateByPrimaryKey(product,cName,cValue,eId);
			session.setAttribute("productId", product.getId()+"");

		}else{               //否则就新增
			iproductService.insert(product,cName,cValue);
			Product p = iproductService.getMaxIdProduct();
			session.setAttribute("productId", p.getId()+"");
		}
		return "redirect:productList?vId="+product.getVId();
		
	}
	
	
	
	
	
	/**
	 * 跳转至编辑页面
	 * @param productId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "editProduct", method = RequestMethod.GET)
	public String edit(String productId, String sign, Model model, HttpServletResponse response, HttpServletRequest request) {

		if(!Common.isEmptyString(productId)){
			logger.error("传入参数为空");
			return "redirect:productList";
		}
		request.getSession().setAttribute("productId", productId);
		ProductView pv = iproductService.selectProductViewById(productId);
		
		
		Image img= new Image();
		img.setPid(Integer.parseInt(productId));
		img.setType(Short.parseShort("1"));
		List<Image> imgList = imageService.getImagesByPidAndType(img);
		model.addAttribute("imgList", imgList);
		
		model.addAttribute("productView",pv);
		model.addAttribute("sign",sign);
		model.addAttribute("imageUrl",QiniuUtil.IMAGEURL);
		if(Common.isEmptyString(sign) && Integer.parseInt(sign) == 1){			
			return "admin/showProduct";//查看产品信息
		}		
		return "admin/editProduct";
	}
	
	/**
	 * 删除产品
	 * @param productId
	 * @return
	 */
	@RequestMapping(value = "deleteProduct", method = RequestMethod.POST)
	public void deleteProduct(String id, HttpServletResponse response,HttpServletRequest request) {
		iproductService.deleteByPrimaryKey(Integer.parseInt(id),request);
		try {
			PrintWriter out = response.getWriter();
			out.print("success");
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 跳转至生成二维码
	 * @param productId
	 * @return
	 */
	@RequestMapping(value = "QRCode", method = RequestMethod.GET)
	public String QRCode(String productId, Model model) {
		if(productId!=null&&!productId.equals("")){
			Product product = iproductService.selectByPrimaryKey(Integer.parseInt(productId));   //根据id查询产品信息
			Vendor vendor = ivendorService.selectByPrimaryKey(product.getVId());       //根据厂商id查询厂商信息
			model.addAttribute("product", product);
			model.addAttribute("vendor", vendor);
		}

		String url = ReadPropertiesUtil.getPropertiesValue("url");
		model.addAttribute("url", url);
		return "admin/QRCode";
	}
	
	/**
	 * 搜索厂商名称
	 * @param vendorName
	 * @param response
	 */
	@RequestMapping(value = "vendorSearch", method = RequestMethod.POST)
	public void search(String vendorName, HttpServletResponse response) {
		List<Vendor> vendors = new ArrayList<Vendor>();

		vendors = iproductService.selectByVendorName(vendorName.trim()); // 根据名称厂商名称信息					

		try {
			JSONArray json = new JSONArray();
			json.addAll(vendors);
			json.listIterator();
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 搜索 产品名称
	 * @param vendorName
	 * @param response
	 */
	@RequestMapping(value = "productSearch", method = RequestMethod.POST)
	public void productSearch(String vendorName, HttpServletResponse response) {
		if(vendorName == null || vendorName.equals("")){
			return;
		}
		List<Product> products = iproductService.selectProductByVendorName(vendorName.trim()); // 根据名称查询产品信息
		try {
			JSONArray json = new JSONArray();
			json.addAll(products);
			json.listIterator();
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 搜索产品信息
	 * @param vendorName
	 * @param response
	 */
	@RequestMapping(value = "search", method = RequestMethod.POST)
	public void searchProInfo(String productId, HttpServletResponse response,HttpSession session) {
		if(productId==null||productId.equals("")){
			return;
		}
		Product product = iproductService.selectByPrimaryKey(Integer.parseInt(productId));
		session.setAttribute("id", product.getId());
		try {
			response.getWriter().print(JSONObject.toJSON(product));
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 生成二维码参数
	 * @param number
	 * @param batchnum
	 * @param isWin
	 * @param productId
	 * @param QRCodeURL
	 * @param model
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "createQRCodeImg",method=RequestMethod.POST)
	@Transactional
	public void createQRCodeImg(String number, String addNum,  String id, String QRCodeURL, 
			String preColor,String bgColor
			,String qrsize,Model model, HttpServletRequest request, HttpServletResponse response){
		//先生成二维码参数，获取二维码参数txt地址
		
		if(!Common.isEmptyString(id)){
			id = (String) request.getSession().getAttribute("id");
		}
		
		int length = 4-id.length();
		for (int k = 0; k < length; k++) {
			id = "0"+id;
		}
		
		String tableName = "qlm_fcrm_qrcode_"+id;        //表名
		String tableName1 = "qlm_portal_scanrecord_"+id;
		int count = iqrcodeService.existTable(tableName);      //判断是否存在该表
		int count1 = iqrcodeService.existTable(tableName1);      //判断是否存在该表
		if(count==0){      //如果不存在，就新建表
			iqrcodeService.createNewTable(tableName);
		}
		if(count1==0){      //如果不存在，就新建表
			iqrcodeService.createScanrecordTable(id);
		}

		Product product = iproductService.selectByPrimaryKey(Integer.parseInt(id));
		Vendor vendor = ivendorService.selectByPrimaryKey(product.getVId());
		String code = id;
		String path = request.getSession().getServletContext().getRealPath("/") + "QRCode";
		
		String sourceFilePath = FileOperation.contentToTxtByThread(iqrcodeService, code, vendor,product, Integer.parseInt(number), path, QRCodeURL ,addNum);
		
		
		
		String filePath="";//图片生成目录
		String fileName = "";
		String zipFilePath="";
		if(sourceFilePath!=null){
			File sourceFile = new File(sourceFilePath);
			if(sourceFile.exists()){
				filePath=sourceFile.getParentFile().getAbsolutePath();
				fileName = sourceFile.getParentFile().getName();
				zipFilePath= sourceFile.getParentFile().getParentFile().getAbsolutePath();
			}
			//根据参数生成二维码图片
			QrcodeConfig config = new QrcodeConfig();
			if(!"".equals(preColor) && null != preColor){
				config.setColor(Integer.parseInt(preColor.substring(1),16));
			}
			if(!"".equals(bgColor) && null != bgColor){
				config.setBgColor(Integer.parseInt(bgColor.substring(1),16));
			}
			config.setHeight(Integer.parseInt(qrsize));
			config.setWidth(Integer.parseInt(qrsize));

			QrcodeFactory.createCodesFromTxt(sourceFilePath, filePath, config, null, null);
			
			//打包文件
		   FileToZip.fileToZip(filePath, zipFilePath, fileName);
		  //下载时候使用，@后面的为下载的文件名称，前面的为服务器文件路径
			String pathName = filePath+".zip"+"@"+fileName;   
			try {
				PrintWriter out= response.getWriter();
				out.print(pathName);
				out.flush();
				out.close();
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		
	}
	
	
	@RequestMapping(value = "createQRCode", method = RequestMethod.POST)
	@Transactional
	public void createQRCode(boolean isImg,String number, String id, String addNum, String QRCodeURL, Model model, 
			HttpServletRequest request, HttpServletResponse response){
		if(!Common.isEmptyString(number) || !Common.isEmptyString(QRCodeURL)){
			return ;
		}
		System.out.println("addNum="+addNum);
		HttpSession session = request.getSession();
		if(!Common.isEmptyString(id)){
			id = (String) session.getAttribute("id");
		}
		
		String tableName = "qlm_fcrm_qrcode_"+id;        //表名
		String tableName1 = "qlm_portal_scanrecord_"+id;

		int count = iqrcodeService.existTable(tableName);      //判断是否存在该表
		int count1 = iqrcodeService.existTable(tableName1);      //判断是否存在该表

		if(count==0){      //如果不存在，就新建表
			iqrcodeService.createNewTable(tableName);
		}
		if(count1==0){      //如果不存在，就新建表
			iqrcodeService.createScanrecordTable(id);
		}

		Product product = iproductService.selectByPrimaryKey(Integer.parseInt(id));
		Vendor vendor = ivendorService.selectByPrimaryKey(product.getVId());
		String code = id;
		String filePath = request.getSession().getServletContext().getRealPath("/") + "QRCode";

		
		int amount = Integer.parseInt(number);

		
		String sourceFilePath = FileOperation.contentToTxtByThread(iqrcodeService, code, vendor,product, amount, filePath, QRCodeURL,addNum);

		//生成图片 这里不作打包
		if(sourceFilePath != null){
				//打包文件
				String fileName = "";
				String zipFilePath="";
				File sourceFile = new File(sourceFilePath);
				if(sourceFile.exists()){
					filePath=sourceFile.getParentFile().getAbsolutePath();

					fileName = sourceFile.getParentFile().getName();

					zipFilePath= sourceFile.getParentFile().getParentFile().getAbsolutePath();

				}
			   FileToZip.fileToZip(filePath, zipFilePath, fileName);
			  //下载时候使用，@后面的为下载的文件名称，前面的为服务器文件路径
			   String pathName = filePath+".zip"+"@"+fileName;   
				try {
					PrintWriter out= response.getWriter();
					out.print(pathName);
					out.flush();
					out.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}


		}

	}
	
	@RequestMapping(value = "saveProductImg", method = RequestMethod.POST)
	public void saveProductImg(HttpServletRequest request, HttpServletResponse response) {
		
		String productId = (String) request.getSession().getAttribute("productId");
		logger.info("method saveVendorImg productId="+productId);
		if(!Common.isEmptyString(productId)){
			return ;
		}
		
		String url = null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){ 
            	//取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){          
                	File targetFile = null;

            		String url1 = getDate.getStringFullDate()+ file.getOriginalFilename();             		
 
            		url = request.getSession().getServletContext().getRealPath("/")
            				+ "uploadImage/" + url1;
            		
                    targetFile = new File(url);                  	
                    if(!targetFile.exists()){  
                        targetFile.mkdirs();  
                    }  
                    //保存  
                    try {                    	
                    	file.transferTo(targetFile);

                    	Image img = new Image();
                    	img.setPid(Integer.parseInt(productId));
                    	img.setImg(url1);
                    	img.setType(Short.parseShort("1"));//0厂商  1产品
                    	if(imageService.insertImage(img) >0){
                    		logger.info("图片信息保存成功");
                    	}else{
                    		logger.info("图片信息保存失败");
                    	}
                    	//上传至七牛云
                    	String success = QiniuUtil.upload(url, url1); // 上传到七牛云服务
        				if (success != null) {
        					targetFile.delete(); // 如果上传成功，就删除本地服务的图片
        				}
                    } catch (Exception e) {  
                       logger.error(e.getMessage());  
                    }  
                }
            }
            
        }
        
	}
	

	
	
}
